﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace MyMedia.iPod
{
    public class iPod
    {
        public static bool iPodConnected = false;
        public static string iPodDriveLetter = "";
        public static bool iPodMounted = false;
        public static string iPodName = "";

        public bool EjectiPod()
        {
            if (iPodMounted && (iPodDriveLetter.Length > 0))
            {
                bool flag = false;
                IntPtr hDevice = CreateFile(@"\\.\" + iPodDriveLetter.Substring(0, 2), -2147483648, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
                if (((int)hDevice) != -1)
                {
                    int lpBytesReturned = 0;
                    flag = DeviceIoControl(hDevice, 0x2d4808, IntPtr.Zero, 0, IntPtr.Zero, 0, ref lpBytesReturned, IntPtr.Zero);
                }
                CloseHandle(hDevice);
                return flag;
            }
            return false;
        }
        public string FindiPod()
        {
            foreach (DriveInfo info in DriveInfo.GetDrives())
            {
                if ((!info.Name.StartsWith("a:") && !info.Name.StartsWith("A:") && !info.Name.StartsWith("b:") && !info.Name.StartsWith("B:")) && File.Exists(info.Name + @"iPod_Control\iTunes\iTunesDB"))
                {
                    return info.Name;
                }
            }
            return string.Empty;
        }

        #region "DLLImports"
        [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern bool DeviceIoControl(IntPtr hDevice, int dwIoControlCode, IntPtr lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped);
        [DllImport("kernel32.dll")]
        internal static extern IntPtr CloseHandle(IntPtr hObject);
        [DllImport("kernel32.dll")]
        public static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetVolumeInformation(string lpRootPathName, StringBuilder lpVolumeNameBuffer, int nVolumeNameSize, out uint lpVolumeSerialNumber, out int lpMaximumComponentLength, out int lpFileSystemFlags, StringBuilder lpFileSystemNameBuffer, int nFileSystemNameSize);
        #endregion
    }
}
